package android.FiltrosJava;

import java.awt.image.*;

public abstract class FiltroConvolucao extends AbstractImageBasic{	
	protected float [][]mask;
	protected int bias;

	public void setMask_Bias(float[][] myMask, int myBias){
		mask = myMask;
		bias = myBias;
	}
	
	public BufferedImage applyFilter(BufferedImage src){
		BufferedImage dst = applyConvolve(src, mask, bias);
    	return dst;
	}		
		
	protected BufferedImage applyConvolve(BufferedImage src, float[][] mask, int bias){
		BufferedImage dst = copiaImagem(src);//createCompatibleDestImage(src);
		
		int width = src.getWidth();
        int height = src.getHeight();            
    	int height_mask = mask.length;
    	int width_mask = mask[0].length;
    	int middle_height = (int) (height_mask / 2);
    	int middle_width = (int) (width_mask / 2);
    	
    	WritableRaster raster_src = src.getRaster();
    	WritableRaster raster_dst = dst.getRaster();
    	int numBands = raster_src.getNumBands();
    	int[] imageData_src = new int[numBands];
    	int[] imageData_dst = new int[numBands];
    	int px;
    	int py;
    	
    	for ( int y = 0; y < height; y++ ) {
    		for ( int x = 0; x < width; x++ ) {
    			imageData_src[0] = 0;
    			imageData_src[1] = 0;
    			imageData_src[2] = 0;
    			
    			for (int my = 0; my < height_mask; my++){
    				for (int mx = 0; mx < width_mask; mx++){
    					px = x + mx - middle_width;
    					py = y + my - middle_height;
    					if ((px >=0) && (px < width) && (py >=0) && (py < height)){
    						raster_dst.getPixel(px,py,imageData_dst);
    						imageData_src[0] = (int) (imageData_src[0] + imageData_dst[0] * mask[my][mx]);
    						imageData_src[1] = (int) (imageData_src[1] + imageData_dst[1] * mask[my][mx]);
    						imageData_src[2] = (int) (imageData_src[2] + imageData_dst[2] * mask[my][mx]);    						
    					}
    				}
    			}    			
    			
    			for (int z = 0; z < 3; z++){
    				imageData_src[z] = delimitaCor(imageData_src[z] + bias);    				    				
    			}    			
				
				raster_src.setPixel(x,y,imageData_src);
    		}
    	}
    	
		dst = null;		
		return src;
	}	
}
